import router from './routers'
import store from '@/store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'// progress bar style
import { getToken } from '@/utils/auth' // getToken from cookie

NProgress.configure({ showSpinner: false })// NProgress Configuration

const whiteList = ['/login']// no redirect whitelist

router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    document.title = to.meta.title + ' - 问卷调查'
  }
  NProgress.start() // start progress bar
  if (getToken()) {
    if (to.path === '/login') {
      next('/')
    } else {
      if (store.getters.addRouters.length === 0) {
        // 生成菜单
        loadMenus(next, to)
      } else {
        next()
      }
    }
    NProgress.done() // if current page is dashboard will not trigger	afterEach hook, so manually handle it
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

export const loadMenus = function(next, to) {
  const asyncRouter = [{ path: '*', redirect: '/404', hidden: true }]
  store.dispatch('GenerateRoutes', asyncRouter).then(() => { // 存储路由
    router.addRoutes(asyncRouter) // 动态添加可访问路由表
    next({ ...to, replace: true })// hack方法 确保addRoutes已完成
  })
}

router.afterEach(() => {
  NProgress.done() // finish progress bar
})
